package com.d3works.apps.sale.web;

import com.d3works.apps.sale.db.ConfiguratorCreator;
import com.d3works.apps.sale.db.ConfiguratorFormula;
import com.d3works.apps.sale.exception.SaleExceptionMessage;
import com.d3works.apps.sale.service.configurator.ConfiguratorFormulaService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;

@Singleton
public class ConfiguratorFormulaController {

  /**
   * Check the groovy script in the context
   *
   * @param request
   * @param response
   */
  public void checkGroovyFormula(ActionRequest request, ActionResponse response) {
    ConfiguratorFormula configuratorFormula =
        request.getContext().asType(ConfiguratorFormula.class);
    ConfiguratorCreator creator =
        request.getContext().getParent().asType(ConfiguratorCreator.class);
    try {
      Beans.get(ConfiguratorFormulaService.class).checkFormula(configuratorFormula, creator);
      response.setAlert(I18n.get(SaleExceptionMessage.CONFIGURATOR_CREATOR_SCRIPT_WORKING));
    } catch (Exception e) {
      response.setError(e.getMessage());
    }
  }
}
